package com.lswms.modules.lswms.controller.base;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.lswms.common.annotation.LogOperation;
import com.lswms.common.constant.Constant;
import com.lswms.common.page.PageData;
import com.lswms.common.utils.ExcelUtils;
import com.lswms.common.utils.Result;
import com.lswms.common.validator.AssertUtils;
import com.lswms.common.validator.ValidatorUtils;
import com.lswms.common.validator.group.AddGroup;
import com.lswms.common.validator.group.DefaultGroup;
import com.lswms.common.validator.group.UpdateGroup;
import com.lswms.modules.lswms.MEGConstant;
import com.lswms.modules.lswms.dao.base.SkuDao;
import com.lswms.modules.lswms.dto.base.SkuDTO;
import com.lswms.modules.lswms.entity.base.SkuEntity;
import com.lswms.modules.lswms.excel.base.SkuExcel;
import com.lswms.modules.lswms.service.base.SkuService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * ${comments}
 *
 * @author DX
 * @since 1.0.0 2021-06-06
 */
@RestController
@RequestMapping("lswms/sku")
@Api(tags = "${comments}")
public class SkuController {
	@Autowired
	private SkuService skuService;

	@Autowired
	private SkuDao skuDao;

	@GetMapping("page")
	@ApiOperation("分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String") })
//	@RequiresPermissions("lswms:sku:page")
	public Result<PageData<SkuEntity>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
//        PageData<SkuDTO> page = skuService.page(params);
		PageData<SkuEntity> page = skuService.selectPageBySql(params);

		return new Result<PageData<SkuEntity>>().ok(page);
	}

	@GetMapping("{id}")
	@ApiOperation("信息")
//	@RequiresPermissions("lswms:sku:info")
	public Result<SkuEntity> get(@PathVariable("id") Long id) {
		SkuEntity data = skuService.getKey(id);

		return new Result<SkuEntity>().ok(data);
	}

	@PostMapping("getSkuByCode")
	@ApiOperation("信息")
//	@RequiresPermissions("lswms:sku:info")
	public Result<SkuEntity> getSkuByCode(@RequestBody String sku) {
		SkuEntity data = skuService.getSkuByCode(sku);
		if(data == null) {
			return new Result<SkuEntity>().error("没有查询到记录") ;
		}
		return new Result<SkuEntity>().ok(data);
	}

	
	@PostMapping
	@ApiOperation("保存")
	@LogOperation("保存")
	@RequiresPermissions("lswms:sku:save")
	public Result save(@RequestBody SkuDTO dto) {

		try {
			// 效验数据
			ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

			String msg = skuService.valideAndSave(dto);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@PutMapping
	@ApiOperation("修改")
	@LogOperation("修改")
	@RequiresPermissions("lswms:sku:update")
	public Result update(@RequestBody SkuDTO dto) {
		try {
			// 效验数据
			ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);


			String msg = skuService.valideAndUpdate(dto);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@DeleteMapping
	@ApiOperation("删除")
	@LogOperation("删除")
	@RequiresPermissions("lswms:sku:delete")
	public Result delete(@RequestBody String[] skus) {
		try {
			// 效验数据
			AssertUtils.isArrayEmpty(skus, "sku");

			String msg = skuService.deleteByKey(skus);
			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@GetMapping("export")
	@ApiOperation("导出")
	@LogOperation("导出")
	@RequiresPermissions("lswms:sku:export")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response)
			throws Exception {
		List<SkuDTO> list = skuService.list(params);

		ExcelUtils.exportExcelToTarget(response, null, list, SkuExcel.class);
	}

	@GetMapping("exportModule")
	@ApiOperation("导出")
	@LogOperation("导出")
	@RequiresPermissions("lswms:sku:exportModule")
	public void exportModule(HttpServletRequest request , HttpServletResponse response)
			throws Exception {

		try {
			String path = "\\WEB-INF\\classes\\statics\\excelMode\\skuModule.xls";
			String excelPath = request.getSession().getServletContext().getRealPath(path) ;
			InputStream  inStream=new FileInputStream(excelPath) ;
			
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("skuModule", "UTF-8") + ".xls");
			
			byte[] b = new byte[2048];
			int len;
			while((len = inStream.read(b))>0) {
				response.getOutputStream().write(b,0,len);
			}
			inStream.close();
			response.getOutputStream().flush();
		}catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
		
	}
	
	
	@PostMapping("importExcel")
	@ApiOperation("导入")
	@LogOperation("导入")
	@RequiresPermissions("lswms:sku:import")
	public Result importExcel(@RequestParam("textFile") MultipartFile file, HttpServletRequest request)
			throws Exception {
		
		try {
			String msg = skuService.importExcel(file);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

}
